<?php
/**
 * Bring Shippingguide - VirtueMart
 * @package VirtueMart
 * @subpackage shipping
 * @copyright Copyright (C) 2011-2012 VirtueMart Team. All rights reserved.
 * @copyright Copyright (C) 2012 fraktpriservirtuemart - Google Code project. All rights reserved.
 * @license License http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL, see LICENSE.txt
 * @version $Id: bring_shippingguide.php 41 2013-10-19 17:07:44Z syntaxerror.no $
 * Ported to VirtueMart 2 and extended by:
 * - Tommy Roger Skålvik - Buskerud Web AS - www.buskerudweb.com
 * - Rune Rasmussen - www.syntaxerror.no
 * TODO: Volum/mål-håndtering
 * TODO: Valg av postkontor, som kunde ønsker levert til, i kasse.
*/

if (!defined('_JEXEC'))
    die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');

if (!class_exists('vmPSPlugin'))
    require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php');

class plgVmShipmentBring_Shippingguide extends vmPSPlugin {

    // instance of class
    public static $_this = false;

    function __construct(& $subject, $config) {
			parent::__construct($subject, $config);
		
			$this->_loggable = true;
			$this->tableFields = array_keys($this->getTableSQLFields());
			$varsToPush = array(
			    'deliveryterm' => array('SERVICEPAKKE', 'char'),
			    'fromzip' => array(0, 'int'),
			    'shipfrompostoffice' => array(0, 'int'),
			    'shipment_logos' => array('', 'char'),
			    'countries' => array(0, 'char'),
			    'cost' => array(0, 'int'),
			    'package_fee' => array(0, 'int'),
			    'tax_id' => array(0, 'int'),
			    'free_shipment' => array(0, 'int')
			);

			$this->setConfigParameterable($this->_configTableFieldName, $varsToPush);								
    }

    /**
     * Create the table for this plugin if it does not yet exist.
     * @author Valérie Isaksen
     */
    protected function getVmPluginCreateTableSQL() {
			return $this->createTableSQL('Shipment Bring Shippingguide Table');
    }

    function getTableSQLFields() {
			$SQLfields = array(
			    'id' => ' tinyint(1) unsigned NOT NULL AUTO_INCREMENT',
			    'virtuemart_order_id' => 'int(11) UNSIGNED DEFAULT NULL',
			    'order_number' => 'char(32) DEFAULT NULL',
			    'virtuemart_shipmentmethod_id' => 'mediumint(1) UNSIGNED DEFAULT NULL',
			    'shipment_name' => 'text NOT NULL DEFAULT \'\' ',
			    'order_weight' => 'decimal(10,4) DEFAULT NULL',
			    'order_length' => 'decimal(10,4) DEFAULT NULL',
			    'order_width' => 'decimal(10,4) DEFAULT NULL',
			    'order_height' => 'decimal(10,4) DEFAULT NULL',
			    'order_volume' => 'decimal(10,4) DEFAULT NULL',
			    'shipment_cost_with_fee' => 'decimal(10,2) DEFAULT NULL',
			    'shipment_package_fee' => 'decimal(10,2) DEFAULT NULL',
			    'tax_id' => 'smallint(1) DEFAULT NULL'
			);
			return $SQLfields;
    }

    /**
     * This method is fired when showing the order details in the frontend.
     * It displays the shipment-specific data.
     *
     * @param integer $order_number The order Number
     * @return mixed Null for shipments that aren't active, text (HTML) otherwise
     * @author Valérie Isaksen
     * @author Max Milbers
     */
    public function plgVmOnShowOrderFEShipment($virtuemart_order_id, $virtuemart_shipmentmethod_id, &$shipment_name) {
								$document =& JFactory::getDocument();
								$themecss = JURI::root() . '/plugins/vmshipment/bring_shippingguide/bring_shippingguide.css';
								$document->addStyleSheet($themecss, 'text/css', "screen");
			
			$this->onShowOrderFE($virtuemart_order_id, $virtuemart_shipmentmethod_id, $shipment_name);
    }

    /**
     * This event is fired after the order has been stored; it gets the shipment method-
     * specific data.
     *
     * @param int $order_id The order_id being processed
     * @param object $cart  the cart
     * @param array $priceData Price information for this order
     * @return mixed Null when this method was not selected, otherwise true
     * @author Valerie Isaksen
     */
    function plgVmConfirmedOrder(VirtueMartCart $cart, $order) {
			if (!($method = $this->getVmPluginMethod($order['details']['BT']->virtuemart_shipmentmethod_id))) {
			    return null; // Another method was selected, do nothing
			}
			if (!$this->selectedThisElement($method->shipment_element)) {
			    return false;
			}
		
			$values['order_number'] = $order['details']['BT']->order_number;
			$values['shipment_id'] = $order['details']['BT']->virtuemart_shipmentmethod_id;
			$values['shipment_name'] = $this->renderPluginName($method);
			$values['order_weight'] = $this->getOrderWeight($cart, 'GR');
			$values['shipment_cost_with_fee'] = $this->fraktArray['cost'];
			$values['shipment_package_fee'] = $method->package_fee;
			$values['tax_id'] = $method->tax_id;
			$this->storePSPluginInternalData($values);
		
			return true;
    }

    /**
     * This method is fired when showing the order details in the backend.
     * It displays the shipment-specific data.
     * NOTE, this plugin should NOT be used to display form fields, since it's called outside
     * a form! Use plgVmOnUpdateOrderBE() instead!
     *
     * @param integer $virtuemart_order_id The order ID
     * @param integer $vendorId Vendor ID
     * @param object $_shipInfo Object with the properties 'shipment' and 'name'
     * @return mixed Null for shipments that aren't active, text (HTML) otherwise
     * @author Valerie Isaksen
     */
    public function plgVmOnShowOrderBEShipment($virtuemart_order_id, $virtuemart_shipmentmethod_id) {
			if (!($this->selectedThisByMethodId($virtuemart_shipmentmethod_id))) {
			    return null;
			}
			
			$html = $this->getOrderShipmentHtml($virtuemart_order_id);
			return $html;
		    }
		
		function getOrderShipmentHtml($virtuemart_order_id) {
			$db = JFactory::getDBO();
			$q = 'SELECT * FROM `' . $this->_tablename . '` '
				. 'WHERE `virtuemart_order_id` = ' . $virtuemart_order_id;
			$db->setQuery($q);
			if (!($shipinfo = $db->loadObject())) {
			    vmWarn(500, $q . " " . $db->getErrorMsg());
			    return '';
			}
		
			if (!class_exists('CurrencyDisplay'))
			    require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php');
		
			$currency = CurrencyDisplay::getInstance();
			$tax = ShopFunctions::getTaxByID($shipinfo->tax_id);
			$taxDisplay = is_array($tax) ? $tax['calc_value'] . ' ' . $tax['calc_value_mathop'] : $shipinfo->tax_id;
			$taxDisplay = ($taxDisplay == -1 ) ? JText::_('COM_VIRTUEMART_PRODUCT_TAX_NONE') : $taxDisplay;
		
			$themecss = file_get_contents(JURI::root() . '/plugins/vmshipment/bring_shippingguide/bring_shippingguide.css');
			
			$html = '<style type="text/css">';
			$html .= $themecss;
			$html .= '</style>';

			$html .= '<table class="adminlist">' . "\n";
			$html .=$this->getHtmlHeaderBE();
			$html .= $this->getHtmlRowBE('BRING_SHIPPINGGUIDE_SHIPPING_NAME', $shipinfo->shipment_name);
			$html .= $this->getHtmlRowBE('BRING_SHIPPINGGUIDE_WEIGHT', $shipinfo->order_weight . ' ' . ShopFunctions::renderWeightUnit('GR'));
			$html .= $this->getHtmlRowBE('BRING_SHIPPINGGUIDE_COST', $currency->priceDisplay($shipinfo->shipment_cost_with_fee, '', false));
			$html .= $this->getHtmlRowBE('BRING_SHIPPINGGUIDE_PACKAGE_FEE', $currency->priceDisplay($shipinfo->shipment_package_fee, '', false));
			$html .= $this->getHtmlRowBE('BRING_SHIPPINGGUIDE_TAX', $taxDisplay);
			$html .= '</table>' . "\n";
		
			return $html;
    }

    function getCosts(VirtueMartCart $cart, $method, $cart_prices) {
			if ($method->free_shipment && $cart_prices['salesPrice'] >= $method->free_shipment) {
			    return 0;
			} else {
					//If the Bring has returned a transport value
					if (isset($this->fraktArray['cost']))
					{
						//The transportvalue is higher than 0. If 0 then we use the default value from the parameters.
						if ($this->fraktArray['cost'] != 0)
						{ 
							$method->cost = $this->fraktArray['cost'];
						}
					}
				
			    return $method->cost + $method->package_fee;
			}
		}
		
		protected function checkConditions($cart, $method, $cart_prices) {
			$orderWeight = $this->getOrderWeight($cart, 'GR'); //Hent ordrens totale vekt i gram.
			
			$address = (($cart->ST == 0) ? $cart->BT : $cart->ST);
		
			$nbShipment = 0;
		
			//Tilordne mottakslandene som modulen gjelder for
			$countries = array();
			if (!empty($method->countries)) {
			    if (!is_array($method->countries)) {
						$countries[0] = $method->countries;
			    } else {
						$countries = $method->countries;
			    }
			} else {
				//Hvis det ikke er angitt noe land legger vi inn Norge og Svalbard/Jan Mayen som standard.
				$countries['0'] = 160; //Norge
				$countries['1'] = 201; //Svalbard og Jan Mayen
			}
						
			//Sjekk om det er angitt bare Norge eller Svalbard i landlisten (dvs. bare en av de).
			//I så fall legger vi til den manglende, slik at begge fortsatt er med i spørringene.
			if (in_array('160', $countries) && !in_array('201', $countries)) $countries[] = 201; //Legger til Svalbard/Jan Mayen.
			if (in_array('201', $countries) && !in_array('160', $countries)) $countries[] = 160; //Legger til Norge.
			
			// probably did not gave his BT:ST address
			if (!is_array($address)) {
			    $address = array();
			    $address['zip'] = 0;
			    $address['virtuemart_country_id'] = 0;
			}
			
			//Sjekk om mottaker er innenfor godkjent land. Hvis ikke er det ikke nødvendig å forespørre Bring.
			if (!isset($address['virtuemart_country_id']))
			    $address['virtuemart_country_id'] = 0;
			if (!in_array($address['virtuemart_country_id'], $countries)) return false;
			

			//Check if there is any products in the cart
			if ($cart->products)
			{
				//Legg CSS-filen inn i siden
				$document =& JFactory::getDocument();
				$themecss = JURI::root() . '/plugins/vmshipment/bring_shippingguide/bring_shippingguide.css';
				$document->addStyleSheet($themecss, 'text/css', "screen");
				
				
				//Hent butikkens nettsideadresse og versjonsnummeret til VirtueMart
				$vmVersion = VmConfig::getInstalledVersion();	//Virtuemart versjonsnummer
				$shopURL = JURI::base(); //Nettadressen til butikken
				$shopURL = preg_replace(array('@h[^>]*?.://www\.@siu','@h[^>]*?.://@siu'), array('',''), $shopURL); //Fjern http/https og www
				
				$userAgent = 'VirtueMart Bring Shippingguide (VM v' . $vmVersion . ' - ' . $shopURL . ')';
				
				//Forbered og gjennomfør oppkall til Bring.
				$productCode = $method->deliveryterm;
				$shipFromPostOffice = $method->shipfrompostoffice;
				$fromCountry = shopFunctions::getCountryByID(160, $fld = 'country_2_code');//TODO: Hent in butikkens egentlige landskode.
				$fromZip = $method->fromzip;
				$toCountry = shopFunctions::getCountryByID($address['virtuemart_country_id'], $fld = 'country_2_code');
				//Dersom Svalbard og Jan Mayen er valgt bruker vi likevell NO.
				if ($toCountry == 'SJ') { $toCountry = 'NO'; }
				$toZip = $address['zip'];
				$shipping_weight = $orderWeight;
				$shipping_num_boxes = 1;
				if ($method->tax_id == -1 || $method->tax_id == 0) $getIncTax = true; else $getIncTax = false;
			
				// getValuesForProduct
				$this->fraktArray = $this->getValuesForProduct($productCode, $fromCountry, $fromZip, $toCountry, $toZip, $shipping_weight, $shipping_num_boxes, $shipFromPostOffice, $getIncTax, $userAgent);

				/*if (isset($this->fraktArray['error']) && $method->cost >= 1) {
					$html = '<div><dl id="system-message" style="display: block;"><dt class="message">Message</dt><dd class="message message"><ul><li>';
					$html .= $this->renderPluginName($method) . ': ' . JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_DEFAULT_COST');
					$html .= '</li></ul></dd></dl><div>';

					print_r($html);
					//return false;
				} else*/if (isset($this->fraktArray['error']) && $this->fraktArray['cost'] <= 0 && $method->cost <= 0) {
					//include_once 'error_display.php';
					define('COM_VIRTUEMART_CART_NO_SHIPMENT_SELECTED', 'VMSHIPMENT_BRING_SHIPPINGGUIDE_NO_SHIPMENT_SELECTED');
					return false;
				}

				//Sett fraktprisen til 0 hvis "Gratis fraktpristerskel" er nådd.
				if ($method->free_shipment > 0) {
					if ($method->free_shipment <= $cart->pricesUnformatted['basePrice']) $this->fraktArray['cost'] = 0;
				}
			}
			else
			  return false; //Det er ingen produkter i handlekurven.
				
			return true; //Vis fraktterm
    }

    /**
     * Create the table for this plugin if it does not yet exist.
     * This functions checks if the called plugin is active one.
     * When yes it is calling the standard method to create the tables
     * @author Valérie Isaksen
     *
     */
    function plgVmOnStoreInstallShipmentPluginTable($jplugin_id) {
			return $this->onStoreInstallPluginTable($jplugin_id);
    }

    /**
     * This event is fired after the shipment method has been selected. It can be used to store
     * additional payment info in the cart.
     *
     * @author Max Milbers
     * @author Valérie isaksen
     *
     * @param VirtueMartCart $cart: the actual cart
     * @return null if the payment was not selected, true if the data is valid, error message if the data is not vlaid
     *
     */
    public function plgVmOnSelectCheck($psType, VirtueMartCart $cart) {
			return $this->OnSelectCheck($psType, $cart);
    }

    /**
     * plgVmDisplayListFE
     * This event is fired to display the pluginmethods in the cart (edit shipment/payment) for exampel
     *
     * @param object $cart Cart object
     * @param integer $selected ID of the method selected
     * @return boolean True on succes, false on failures, null when this plugin was not selected.
     * On errors, JError::raiseWarning (or JError::raiseError) must be used to set a message.
     *
     * @author Valerie Isaksen
     * @author Max Milbers
     */
    public function plgVmDisplayListFEShipment(VirtueMartCart $cart, $selected = 0, &$htmlIn) {
			return $this->displayListFE($cart, $selected, $htmlIn);
    }

    /*
     * plgVmonSelectedCalculatePrice
     * Calculate the price (value, tax_id) of the selected method
     * It is called by the calculator
     * This function does NOT to be reimplemented. If not reimplemented, then the default values from this function are taken.
     * @author Valerie Isaksen
     * @cart: VirtueMartCart the current cart
     * @cart_prices: array the new cart prices
     * @return null if the method was not selected, false if the shiiping rate is not valid any more, true otherwise
     *
     *
     */

    public function plgVmonSelectedCalculatePriceShipment(VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) { 
			return $this->onSelectedCalculatePrice($cart, $cart_prices, $cart_prices_name);
    }

    /**
     * plgVmOnCheckAutomaticSelected
     * Checks how many plugins are available. If only one, the user will not have the choice. Enter edit_xxx page
     * The plugin must check first if it is the correct type
     * @author Valerie Isaksen
     * @param VirtueMartCart cart: the cart object
     * @return null if no plugin was found, 0 if more then one plugin was found,  virtuemart_xxx_id if only one plugin is found
     *
     */
    function plgVmOnCheckAutomaticSelectedShipment(VirtueMartCart $cart, array $cart_prices = array()) {
			return $this->onCheckAutomaticSelected($cart, $cart_prices);
    }

    /**
     * This method is fired when showing when priting an Order
     * It displays the the payment method-specific data.
     *
     * @param integer $_virtuemart_order_id The order ID
     * @param integer $method_id  method used for this order
     * @return mixed Null when for payment methods that were not selected, text (HTML) otherwise
     * @author Valerie Isaksen
     */
    function plgVmonShowOrderPrint($order_number, $method_id) {
			return $this->onShowOrderPrint($order_number, $method_id);
    }


    function plgVmDeclarePluginParamsShipment($name, $id, &$data) {
			return $this->declarePluginParams('shipment', $name, $id, $data);
    }

    function plgVmSetOnTablePluginParamsShipment($name, $id, &$table) {
			return $this->setOnTablePluginParams($name, $id, $table);
    }
    
    
		protected function renderPluginName($plugin) {
			$return = '';
			$plugin_name = $this->_psType . '_name';
			$plugin_desc = $this->_psType . '_desc';
			$final_plugin_name = '';
			$final_plugin_desc = '';
			$description = '';
			$transportdays = '';
			$displayname = '';
			$helptext = "";
			$logosFieldName = $this->_psType . '_logos';
			$logos = $plugin->$logosFieldName;
			if (!empty($logos)) {
			    $return = $this->displayLogos($logos) . ' ';
			}
			
			//Get the transport help text for the Bring transport term
			if (isset($this->fraktArray['helptext']))
			{
			  $helptext = '<span class="' . $this->_type . '_bring_helptext">' . $this->fraktArray['helptext'] . '</span>';
			}
			//Get the description of the Bring transport term
			if (isset($this->fraktArray['description']))
			{
				$final_plugin_desc = $this->fraktArray['description'];
			} else {	
				$final_plugin_desc = $plugin->$plugin_desc;
			}
			if (!empty($final_plugin_desc)) {
			    $description = '<span class="' . $this->_type . '_bring_description">' . $final_plugin_desc . '</span>';
			}/* elseif ($this->fraktArray['cost'] <= 0) {
			    $helptext = '<span class="' . $this->_type . '_bring_note">' . JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_DEFAULT_COST') . '</span>';
			}*/
			
			//Get the transportdays for the Bring transport term
			if (isset($this->fraktArray['workingdays']))
			{
			  $transportdays = '<span class="' . $this->_type . '_bring_transportdays">' . $this->fraktArray['workingdays'] . '</span>';
			}

			//Get the displayname from Bring
			if (isset($this->fraktArray['displayname']))
			{
			  $displayname = '<span class="' . $this->_type . '_bring_displayname">' . $this->fraktArray['displayname'] . '</span>';
			}
			
			//Get the productname from Bring
			if (isset($this->fraktArray['productname']))
			{
				$final_plugin_name = $this->fraktArray['productname'];
			} else {
				$final_plugin_name = $plugin->$plugin_name;
			}
				
			$pluginName = $return . '<span class="' . $this->_type . '_bring_name">' . $final_plugin_name . '</span>' . $transportdays . $displayname . $description . $helptext ;			
			
			return $pluginName;
   }    
    

		//API Calls to Bring and preparation of values.
		
		function getValuesForProduct($productCode, $fromCountry, $fromZip, $toCountry, $toZip, $shipping_weight, $shipping_num_boxes, $postingAtPostoffice, $getIncTax, $userAgent) {
			$weightInGrams = round($shipping_weight);
			
			$result = $this->getXmlForProducts($productCode, $fromCountry, $fromZip, $toCountry, $toZip, $weightInGrams, $postingAtPostoffice, $userAgent);
			
			if (isset($result['xml'])) {
				$xml = $result['xml'];
				if ($getIncTax) $priceElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/Price/PackagePriceWithoutAdditionalServices/AmountWithVAT');  //hent ut pris med moms
				else $priceElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/Price/PackagePriceWithoutAdditionalServices/AmountWithoutVAT');  //hent ut pris uten moms
				$productNameElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/GuiInformation/ProductName');  //offisielt produktnavn
				$displayNameElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/GuiInformation/DisplayName');  //nettbutikkvennlig produktnavn
				$descriptionTextElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/GuiInformation/DescriptionText');  //beskrivelsestekst
				$helpTextElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/GuiInformation/HelpText');  //hjelpetekst
				$workingDaysElement = $xml->xpath('/Package/Product[ProductId=\'' . $productCode . '\']/ExpectedDelivery/WorkingDays');  //antall transportdager
				
				if ($priceElement != null) {
				  //Define if workingday or workingdays
				  if($workingDaysElement[0] == 1) {
					 $workingdays = ' ' . JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_WORKINGDAY');
					} elseif ($workingDaysElement[0] > 1) {
					 $workingdays = ' ' . JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_WORKINGDAYS');
					} else {
					 $workingdays = JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_UNKNOWN');
					}
					
					$fraktArray = array(
						'cost' => $fraktpris = ceil(floatval($priceElement[0])*$shipping_num_boxes), //gang pris med antall kolli og rund opp til nærmeste hele krone
						'productname' => strval($productNameElement[0]),
						'displayname' => strval($displayNameElement[0]),
						'workingdays' => JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_EXPECTED_DELIVERY') . ' ' . strval($workingDaysElement[0]) . $workingdays,
						'helptext' => strval($helpTextElement[0]),
						'description' => strval($descriptionTextElement[0]),
					);
				} else {
					$fraktArray['error'] = JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_NOT_AVAILABLE_CART');
				}
				//free memory - just in case...
				unset($xml);
				unset($priceElement);
				unset($productNameElement);
				unset($displayNameElement);
				unset($descriptionTextElement);
				unset($workingDaysElement);
			} else {
				$fraktArray['error'] = $result['error'];
			}
			return $fraktArray;
		}

		function getXmlForProducts($productCode, $fromCountry, $fromZip, $toCountry, $toZip, $weightInGrams, $postingAtPostoffice, $userAgent) {
			$httpclient = JPATH_BASE . DS . 'plugins' . DS . 'vmshipment' . DS . 'bring_shippingguide' . DS . 'http_client.php';

			include_once $httpclient;
	
			$http = new httpClient();
			$http->timeout = 2;
			$request = join('&', array('fromCountry=' . $fromCountry,
									   'from=' . $fromZip,
									   'toCountry=' . $toCountry,
									   'to=' . $toZip,
									   'weightInGrams=' . $weightInGrams,
									   'postingAtPostoffice=' . $postingAtPostoffice));
			if ($http->Connect('fraktguide.bring.no', 80)) {
				$http->addHeader('Host', 'fraktguide.bring.no');
				$http->addHeader('User-Agent', $userAgent);
				$http->addHeader('Connection', 'close');
		
				if ($http->Get('/fraktguide/products/' . $productCode . '/all.xml?' . $request)) {
					$body = $http->getBody();
					if ($http->reply == 200) {
						$result['xml'] = new SimpleXMLElement($body);
					} else {
						if (strpos($body, "FG_INPUT_021")) {
							$result['error'] = JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_021');
						} elseif (strpos($body, "FG_INPUT_022")) {
							$result['error'] = JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_022');
						} elseif (strpos($body, "FG_INPUT_002")) {
							$result['error'] = JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_002');
						} else {
							$result['error'] = JText::_('VMSHIPMENT_BRING_SHIPPINGGUIDE_ERROR_GENERIC');
						}
					}
				}
				$http->Disconnect();
		    }
			return $result;
		}

}

// No closing tag
